package gacl.javaweb12.session;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 首页：列出所有书
 */
@WebServlet("/IndexServlet")
public class IndexServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter pw = response.getWriter();
		//创建Session
		request.getSession();
		pw.write("本网站有如下书：<br/>");
		Set<Map.Entry<String, Book>> set = DB.getAll().entrySet();
		for(Map.Entry<String, Book> me:set){
			Book book = me.getValue();
			String url = request.getContextPath() + "/BuyServlet?id=" + book.getId();
			//response.encodeURL(java.lang.String url)用于对表单action和超链接的url地址进行重写
			url = response.encodeURL(url);//将超链接的url地址进行重写
			pw.println(book.getName() + "<a href='"+url+"'>购买</a><br/>");
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
